package cn.gz.ibix.util;

import android.text.TextUtils;

import com.google.gson.Gson;

import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Function;
import lombok.Data;
import okhttp3.OkHttpClient;

/**
 * 项目名称：QiYiChuAPP
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2018/3/24 11:15
 * <br>修改人:
 * <br>修改时间：2018/3/24 11:15
 * <br>修改备注：
 * <br>@version
 */

@Data
public class HttpUtil {
    private static final String TAG = "HttpUtil";
    private Gson gson = new Gson();

    private HttpUtil() {

    }

    public static HttpUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public <T> void request(final RequestUtil requestUtil) {
     /*   OkHttpClient client = getClient();
        Request.Builder builder = new Request.Builder();
        String url = BuildConfig.API_URL + requestUtil.api();
        Log.d(TAG, "request: url  " + url);
        Log.d(TAG, "request: parms  " + requestUtil.params());
        if (requestUtil.type() == RequestUtil.Type.GET) {
            url += parseParam(requestUtil.params());
        }
        final CallBack callBack = requestUtil.callBack();
        client.newCall(builder.url(url).build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                e.printStackTrace();
                if (callBack != null) {
                    callBack.onFail(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                JsonObject jsonObject = gson.fromJson(body, JsonObject.class);
                if (callBack == null) {
                    return;
                }
                if (jsonObject.get("status").getAsInt() == 0) {
                    callBack.onSuccess(jsonObject.get("data"));
                } else {
                }
            }
        });*/
    }

    public String parseParam(Map<String, String> params) {
        String paramStr = Flowable.fromIterable(params.entrySet()).map(new Function<Map.Entry<String, String>, String>() {
            @Override
            public String apply(Map.Entry<String, String> entry) throws Exception {
                return entry.getKey() + "=" + entry.getValue();
            }
        }).reduce(new BiFunction<String, String, String>() {
            @Override
            public String apply(String s, String s2) throws Exception {
                return s + "&" + s2;
            }
        }).blockingGet("");
        return TextUtils.isEmpty(paramStr) ? "" : "?" + paramStr;
    }

    private OkHttpClient getClient() {
        OkHttpClient okHttpClient = new OkHttpClient();
        return okHttpClient;
    }

    private static class SingletonHolder {
        private static final HttpUtil INSTANCE = new HttpUtil();
    }

}
